package club.wx3609.images.Reptile.service;

import club.wx3609.images.entity.Image;
import club.wx3609.images.service.ImageService;
import com.wx3609_zlj.reptile.start.GetData;
import com.wx3609_zlj.reptile.utils.Connection;
import com.wx3609_zlj.reptile.utils.GetHttpClient;
import com.wx3609_zlj.reptile.utils.HttpType;
import com.wx3609_zlj.utils.CharacterProcessing.DivisionString;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GetImages {

    @Resource
    private ImageService imageService;

    private String charset="utf-8";
    private final static String FileAddress=GetImages.class.getClassLoader().getResource("").getPath()+"static/file";
    public GetImages(){

    }

    public GetImages(String charset){
        this.charset=charset;
    }

    /**
     * 获取图片信息
     * @param url
     * @param ImageTag
     * @param ImageNameTag
     * @return
     * @throws Exception
     */
    public Map<String,String> getImageMessage(String url, String ImageTag, String ImageNameTag) throws Exception {
        Map<String,String> map=new HashMap<String,String>();
        try {
            Elements ImageSrcElements= GetData.getElements(url, ImageTag, HttpType.GET, null,charset);
            Elements ImageTitleElements= GetData.getElements(url, ImageNameTag, HttpType.GET, null,charset);
            int UrlsLength=ImageSrcElements.size();
            if(ImageSrcElements.size()>ImageTitleElements.size()){
                UrlsLength=ImageTitleElements.size();
            }
            for(int i=0;i<UrlsLength;i++){
                String ImageSrc=ImageSrcElements.get(i).attr("src");
                if(ImageSrc.equals("")) {
                    ImageSrc=ImageSrcElements.get(i).attr("data-src");
                }
                if(ImageSrc.equals("")) {
                    break;
                }else {
                    String ImageTitle=ImageTitleElements.get(i).text();
                    map.put(ImageTitle,ImageSrc);
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 获取图片
     * @param map
     */
    @Async
    public int ObtainImage(Map<String,String> map) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        int num=0;
        try {
            for(String key:map.keySet()) {
                String ImageSrc=map.get(key);
                List<Image> list=imageService.findImageUrlPath(ImageSrc);
                if(list.size()==0) {
                    CloseableHttpResponse Response = Connection.connection(GetHttpClient.Connection(), ImageSrc, HttpType.GET, null);
                    String Suffix = DivisionString.spotBehind(ImageSrc, '.');
                    String ImageName = new Date().getTime() + "";
                    String pic = ImageName + "." + Suffix;
                    OutputStream outputstream = new FileOutputStream(new File(FileAddress + "/" + pic));
                    Response.getEntity().writeTo(outputstream);
                    Image image = new Image();
                    image.setImageName(key);
                    image.setImageUrlPath(map.get(key));
                    image.setImageLocalPath(FileAddress+"/"+pic);
                    image.setImageSaveDate(simpleDateFormat.format(new Date()));
                    imageService.addImage(image);
                    outputstream.close();
                    num++;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }

}
